package ru.ognick.option;

import java.io.File;
import ru.ognick.R;
import ru.ognick.core.CoachActivity;
import ru.ognick.locale.ILocale;
import ru.ognick.locale.Locale;
import ru.ognick.utils.FileManager;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class OptionsManager {
	final private CoachActivity own;
	final private ILocale L = Locale.get(); 
	private File[] loadList = new File[0];

	public OptionsManager(CoachActivity own) {
		this.own = own;
	}

	private boolean mem(File file) {
		for (int i = 0; i < loadList.length; ++i)
			if (loadList[i] != null
					&& loadList[i].getName().equals(file.getName())) {
				loadList[i] = null;
				return true;
			}
		return false;
	}

	public void build() {
		File[] curList = FileManager.getFiles("js");
		if (!curList.equals(loadList)) {
			LinearLayout options = (LinearLayout) own
					.findViewById(R.id.linearLayout2);
			for (final File file : curList) {
				if (!mem(file)) {
					LinearLayout topLayout = new LinearLayout(own);
					topLayout.setOrientation(LinearLayout.HORIZONTAL);
					topLayout.setTag(file.getName());

					Button textButton = new Button(own);
					textButton
							.setLayoutParams(new LayoutParams(
									LayoutParams.FILL_PARENT,
									LayoutParams.WRAP_CONTENT));
					textButton.setText(file.getName());
					textButton.setOnClickListener(new OnClickListener() {
					
						public void onClick(View v) {
							own.processManager.load(file);
						}
					});

					Button editButton = new Button(own);
					editButton.setText(L.G_BUTTON_EDIT());
					editButton.setOnClickListener(new OnClickListener() {
					
						public void onClick(View v) {
							Intent editor = new Intent(own,
									EditorActivity.class);
							editor.putExtra("FILE", file);
							own.startActivity(editor);

						}
					});

					Button delButton = new Button(own);
					delButton.setText(L.G_BUTTON_DELETE());
					delButton.setOnClickListener(new OnClickListener() {
					
						public void onClick(View v) {
							FileManager.delete(file);
							build();
						}
					});

					topLayout.addView(editButton);
					topLayout.addView(delButton);
					topLayout.addView(textButton);

					options.addView(topLayout);
				}
			}

			for (final File file : loadList) {
				if (file != null) {
					LinearLayout depricate = (LinearLayout) options
							.findViewWithTag(file.getName());
					options.removeView(depricate);
				}
			}

			loadList = curList;
		}
	}
}